﻿namespace FiftyOne.Foundation.Mobile.Detection.Wurfl.Matchers
{
    using System;

    internal class Algorithms
    {
        internal static int EditDistance(string str1, string str2, int maxValue)
        {
            if (str1 == null)
            {
                throw new ArgumentNullException("str1 can not be null.");
            }
            if (str2 == null)
            {
                throw new ArgumentNullException("str2 can not be null.");
            }
            int length = str1.Length;
            int num2 = str2.Length;
            if (length == 0)
            {
                return num2;
            }
            if (num2 == 0)
            {
                return length;
            }
            int index = 0;
            int num4 = 1;
            int[][] numArray = new int[][] { new int[length + 1], new int[length + 1] };
            int num5 = 0;
            while (num5 <= length)
            {
                numArray[index][num5] = num5;
                num5++;
            }
            for (int i = 1; i <= num2; i++)
            {
                int num7 = 0x7fffffff;
                numArray[num4][0] = i;
                for (num5 = 1; num5 <= length; num5++)
                {
                    int num8 = Math.Min(numArray[index][num5] + 1, Math.Min((int) (numArray[num4][num5 - 1] + 1), (int) (numArray[index][num5 - 1] + ((str1[num5 - 1] == str2[i - 1]) ? 0 : 1))));
                    numArray[num4][num5] = num8;
                    if (num8 < num7)
                    {
                        num7 = num8;
                    }
                }
                if (num7 > maxValue)
                {
                    return 0x7fffffff;
                }
                if (index == 0)
                {
                    index = 1;
                    num4 = 0;
                }
                else
                {
                    index = 0;
                    num4 = 1;
                }
            }
            return numArray[index][length];
        }
    }
}

